package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// GroupBuyVerifyController 团购券核销控制器
type GroupBuyVerifyController struct {
	web.Controller
}

// GroupBuyVerifyListRequest 团购券核销列表请求参数
type GroupBuyVerifyListRequest struct {
	Page             int    `json:"page" form:"page"`
	PageSize         int    `json:"pageSize" form:"pageSize"`
	GroupBuyActivityId int64  `json:"group_buy_activity_id" form:"group_buy_activity_id"`
	MemberId         int64  `json:"member_id" form:"member_id"`
	StoreId          int64  `json:"store_id" form:"store_id"`
	OrderNo          string `json:"order_no" form:"order_no"`
	StartTime        int64  `json:"start_time" form:"start_time"`
	EndTime          int64  `json:"end_time" form:"end_time"`
}

// List 获取团购券核销记录列表
func (c *GroupBuyVerifyController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)
	groupBuyActivityId, _ := c.GetInt64("group_buy_activity_id", 0)
	memberId, _ := c.GetInt64("member_id", 0)
	storeId, _ := c.GetInt64("store_id", 0)
	orderNo := c.GetString("order_no")
	startTimeStr := c.GetString("start_time")
	endTimeStr := c.GetString("end_time")

	// 构建过滤条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	if groupBuyActivityId > 0 {
		// 验证团购活动权限
		if permResult.Admin.FranchiseId > 0 {
			activity, err := models.GetGroupBuyActivityById(groupBuyActivityId)
			if err != nil || activity == nil || activity.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = utils.ResponseFail("无权查看该团购活动的核销记录")
				c.ServeJSON()
				return
			}
		}
		filters["group_buy_activity_id"] = groupBuyActivityId
	}

	if memberId > 0 {
		// 验证会员权限
		if permResult.Admin.FranchiseId > 0 {
			member, err := models.GetMemberById(memberId, permResult.Admin.FranchiseId)
			if err != nil || member == nil || member.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = utils.ResponseFail("无权查看该会员的核销记录")
				c.ServeJSON()
				return
			}
		}
		filters["member_id"] = memberId
	}

	if storeId > 0 {
		// 验证门店权限
		if permResult.Admin.FranchiseId > 0 {
			store, err := models.GetStoreById(storeId)
			if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = utils.ResponseFail("无权查看该门店的核销记录")
				c.ServeJSON()
				return
			}
		}
		filters["store_id"] = storeId
	}

	if orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 处理时间范围
	if startTimeStr != "" {
		startTime, err := time.ParseInLocation("2006-01-02 15:04:05", startTimeStr, time.Local)
		if err == nil {
			filters["start_time"] = startTime.Unix()
		}
	}

	if endTimeStr != "" {
		endTime, err := time.ParseInLocation("2006-01-02 15:04:05", endTimeStr, time.Local)
		if err == nil {
			filters["end_time"] = endTime.Unix()
		}
	}

	// 获取核销记录列表
	verifies, total, err := models.GetGroupBuyVerifyList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = utils.ResponseFail("获取团购券核销记录列表失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 构建响应数据
	list := make([]map[string]interface{}, 0)
	for _, verify := range verifies {
		// 获取团购活动信息
		activity, _ := models.GetGroupBuyActivityById(verify.GroupBuyActivityId)

		// 获取会员信息
		member, _ := models.GetMemberById(verify.MemberId, permResult.Admin.FranchiseId)

		// 获取门店信息
		store, _ := models.GetStoreById(verify.StoreId)

		// 获取操作员信息
		operator, _ := models.GetAdminById(verify.OperatorId)

		item := map[string]interface{}{
			"id":                    verify.Id,
			"group_buy_activity_id": verify.GroupBuyActivityId,
			"group_buy_order_id":    verify.GroupBuyOrderId,
			"member_id":             verify.MemberId,
			"order_id":              verify.OrderId,
			"order_no":              verify.OrderNo,
			"store_id":              verify.StoreId,
			"operator_id":           verify.OperatorId,
			"verify_time":           time.Unix(verify.VerifyTime, 0).Format("2006-01-02 15:04:05"),
			"order_amount":          verify.OrderAmount,
			"remark":                verify.Remark,
			"created_at":            time.Unix(verify.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		}

		// 添加关联信息
		if activity != nil {
			item["activity_name"] = activity.Name
		}

		if member != nil {
			item["username"] = member.Name
		}

		if store != nil {
			item["store_name"] = store.Name
		}

		if operator != nil {
			item["operator_name"] = operator.Username
		}

		list = append(list, item)
	}

	// 返回响应
	c.Data["json"] = utils.ResponseSuccess("OK", map[string]interface{}{
		"list":  list,
		"total": total,
		"page":  page,
	})
	c.ServeJSON()
}

// GetOne 获取团购券核销记录详情
func (c *GroupBuyVerifyController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = utils.ResponseFail("无效的ID参数")
		c.ServeJSON()
		return
	}

	// 获取核销记录
	verify, err := models.GetGroupBuyVerifyById(id)
	if err != nil {
		c.Data["json"] = utils.ResponseFail("获取团购券核销记录失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 权限验证：加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		// 获取团购活动信息验证权限
		activity, err := models.GetGroupBuyActivityById(verify.GroupBuyActivityId)
		if err != nil || activity == nil || activity.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = utils.ResponseFail("无权查看该核销记录")
			c.ServeJSON()
			return
		}

		// 获取门店信息验证权限
		store, err := models.GetStoreById(verify.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = utils.ResponseFail("无权查看该核销记录")
			c.ServeJSON()
			return
		}
	}

	// 获取关联信息
	activity, _ := models.GetGroupBuyActivityById(verify.GroupBuyActivityId)
	member, _ := models.GetMemberById(verify.MemberId, permResult.Admin.FranchiseId)
	store, _ := models.GetStoreById(verify.StoreId)
	operator, _ := models.GetAdminById(verify.OperatorId)

	// 构建响应数据
	data := map[string]interface{}{
		"id":                    verify.Id,
		"group_buy_activity_id": verify.GroupBuyActivityId,
		"group_buy_order_id":    verify.GroupBuyOrderId,
		"member_id":             verify.MemberId,
		"order_id":              verify.OrderId,
		"order_no":              verify.OrderNo,
		"store_id":              verify.StoreId,
		"operator_id":           verify.OperatorId,
		"verify_time":           time.Unix(verify.VerifyTime, 0).Format("2006-01-02 15:04:05"),
		"order_amount":          verify.OrderAmount,
		"remark":                verify.Remark,
		"created_at":            time.Unix(verify.CreatedAt, 0).Format("2006-01-02 15:04:05"),
	}

	// 添加关联信息
	if activity != nil {
		data["activity_name"] = activity.Name
	}

	if member != nil {
		data["username"] = member.Name
	}

	if store != nil {
		data["store_name"] = store.Name
	}

	if operator != nil {
		data["operator_name"] = operator.Username
	}

	// 返回响应
	c.Data["json"] = utils.ResponseSuccess("OK", data)
	c.ServeJSON()
}

// Create 创建团购券核销记录
func (c *GroupBuyVerifyController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		GroupBuyOrderId int64  `json:"group_buy_order_id"`
		StoreId         int64  `json:"store_id"`
		Remark          string `json:"remark"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = utils.ResponseFail("参数解析失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 参数验证
	if req.GroupBuyOrderId <= 0 || req.StoreId <= 0 {
		c.Data["json"] = utils.ResponseFail("参数错误")
		c.ServeJSON()
		return
	}

	// 权限验证：加盟商管理员只能操作自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		// 验证门店权限
		store, err := models.GetStoreById(req.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = utils.ResponseFail("无权在该门店核销团购券")
			c.ServeJSON()
			return
		}

		// 验证团购订单权限
		order, err := models.GetGroupBuyOrderById(req.GroupBuyOrderId)
		if err != nil || order == nil {
			c.Data["json"] = utils.ResponseFail("团购订单不存在")
			c.ServeJSON()
			return
		}

		activity, err := models.GetGroupBuyActivityById(order.ActivityId)
		if err != nil || activity == nil || activity.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = utils.ResponseFail("无权核销该团购券")
			c.ServeJSON()
			return
		}
	}

	// 核销团购券
	err := models.VerifyGroupBuyOrder(
		req.GroupBuyOrderId,
		req.StoreId,
		permResult.Admin.Id,
		req.Remark,
	)

	if err != nil {
		c.Data["json"] = utils.ResponseFail("核销团购券失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = utils.ResponseSuccess("OK", nil)
	c.ServeJSON()
}
